﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using S9Engine;


public partial class Category : Parser
{
    List<ListCategory> _listCategory;
    List<SelectCategory> _selectCategory;

    string _filter;
    string _categoryType;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            InitAll();

            Session["CurrentPage"] = "Category.aspx";
            
            if (!CheckLogin()) Response.Redirect("login.aspx");
            _parser.SetCurrentDir("~/html");
            _parser.SetLanguageFile("~/templates/language.txt", _currentLanguage);
            
            string type = Request["type"] ?? "default";
            string pageIndex = "0";
            string categoryPage = string.Empty;

            _filter = Request["filter"] ?? "news";

            switch (_filter)
            {
                case "news": _categoryType = "news-category"; categoryPage = "category"; pageIndex = "0"; break;
                case "product": _categoryType = "product-category"; categoryPage = "category"; pageIndex = "1"; break;
                case "gallery": _categoryType = "gallery-category"; categoryPage = "gallery"; pageIndex = "5"; break;
            }

            _parser.Assign("currentPageIndex", pageIndex);
            _parser.Assign("currentPageFilter", _filter);
            _parser.Assign("categoryPage", categoryPage);

            _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Terms);
            _DR.Refresh(System.Data.Objects.RefreshMode.StoreWins, _DR.Taxonomy);

            switch (type)
            {
                case "default":
                    {
                        LoadFile("category.html", false);
                        LoadCategories();
                        break;
                    }
                case "add":
                    {
                        LoadFile("category_add.html", false);
                        LoadCategoriesByID(null);
                        break;
                    }
                case "edit":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("category.aspx?filter=" + _filter);
                        }
                        else
                        {
                            LoadFile("category_add.html", false);
                            LoadCategoriesByID(long.Parse(Request["id"]));
                        }
                        break;
                    }
                case "delete":
                    {
                        if (Request["id"] == null)
                        {
                            Response.Redirect("category.aspx?filter=" + _filter);
                        }
                        else
                        {
                            DeleteCategoriesByID(long.Parse(Request["id"]));
                            Response.Redirect("category.aspx?filter=" + _filter);
                        }
                        break;
                    }
                default: goto case "default";
            }
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
        finally
        {
            _parser.Parse("Main");
            _parser.Out("Main");
        }
    }

    private void LoadCategories()
    {
        try
        {
            _listCategory = (from term in _DR.Terms
                             join taxonomy in _DR.Taxonomy on term.ID equals taxonomy.Term
                             where taxonomy.Name.Equals(_categoryType) && taxonomy.LanguageCode.Equals(_currentLanguage)
                             orderby term.ID descending
                             select new ListCategory()
                             {
                                 ID = term.ID,
                                 Name = term.Name,
                                 Parent = taxonomy.Parent,
                                 Description = taxonomy.Description,
                             }).ToList();

            string search = Request["search"] ?? string.Empty;

            BuildListCategory = (ParentId, Level) =>
            {
                return (from c in _listCategory
                        where c.Parent == ParentId
                        from t in new List<ListCategory>()
                        {
                            new ListCategory()
                            {
                                ID = c.ID,
                                Name = new String('-', Level).Replace("-", "&mdash; ") + c.Name,
                                Description = c.Description,
                                Parent = c.Parent
                            }
                        }.Union(BuildListCategory(c.ID, Level + 1))
                        select t).ToList();
            };

            _listCategory = BuildListCategory(0, 0);

            if (!string.IsNullOrEmpty(search))
            {
                _listCategory = _listCategory.Where(n => n.Name.ToLower().Contains(search.ToLower()) || n.Description.ToLower().Contains(search.ToLower())).ToList();

                _parser.Assign("searchValue", search);
            }

            double totalRecord = _listCategory.Count();
            int page = int.Parse(Request["page"] ?? "1");
            int pageSize = _rowsPerPage;
            int totalPage = (int)(totalRecord / pageSize);

            if (totalPage * pageSize < totalRecord) totalPage++;

            if (totalRecord != 0)
            {
                int startRecord = (page == 1 ? 0 : ((page - 1) * pageSize));
                int endRecord = (int)(page * pageSize > totalRecord ? totalRecord : page * pageSize);

                for (int i = startRecord; i < endRecord; i++)
                {
                    _parser.Assign("categoryID", _listCategory.ToList()[i].ID.ToString());
                    _parser.Assign("categoryName", _listCategory.ToList()[i].Name.Replace("<br/>",""));
                    _parser.Assign("categoryParent", _listCategory.ToList()[i].Parent.ToString());
                    _parser.Assign("categoryDescription", _listCategory.ToList()[i].Description);
                    _parser.Parse("Main.Content.Table.TableItem");
                }

                _parser.Assign("totalPage", totalPage.ToString());
                _parser.Assign("totalRecord", totalRecord.ToString());
                _parser.Assign("currentPage", page.ToString());

                if (totalPage != 1)
                {
                    int pagingPage = page / _pageRange;
                    int startPage = 1;
                    int endPage = 1;

                    if (page % _pageRange == (_pageRange - 1) && page > _pageRange)
                    {
                        startPage = page;
                    }
                    else
                    {
                        startPage = (pagingPage * _pageRange == 0 ? 1 : pagingPage * _pageRange);
                    }

                    endPage = (startPage + (_pageRange - 1) > totalPage ? totalPage : startPage + (_pageRange - 1));

                    _parser.Assign("pageIndexPrevious", (page == 1 ? 1 : page - 1).ToString());
                    _parser.Assign("pageIndexNext", (page == totalPage ? totalPage : page + 1).ToString());


                    for (int i = startPage; i <= endPage; i++)
                    {
                        _parser.Assign("currentPageStyle", page == i ? " class=\"current\"" : string.Empty);

                        if (!string.IsNullOrEmpty(search)) _parser.Assign("searchInfo", string.Format("&search={0}", search));

                        _parser.Assign("pageIndex", i.ToString());
                        _parser.Parse("Main.Content.Table.Paging.PagingItem");
                    }

                    _parser.Parse("Main.Content.Table.Paging.PagingPrevious");
                    _parser.Parse("Main.Content.Table.Paging.PagingNext");
                }

                _parser.Parse("Main.Content.Table.Paging");
                _parser.Parse("Main.Content.Table");
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void LoadCategoriesByID(long? ID)
    {
        try
        {
            _selectCategory = (from term in _DR.Terms
                               join taxonomy
                                   in _DR.Taxonomy on term.ID equals taxonomy.Term
                               where taxonomy.Name.Equals(_categoryType) && taxonomy.LanguageCode.Equals(_currentLanguage)
                               select new SelectCategory()
                               {
                                   ID = term.ID,
                                   Name = term.Name,
                                   Parent = taxonomy.Parent
                               }).ToList();

            BuildSelectCategory = (ParentId, Level) =>
            {
                return (from c in _selectCategory
                        where c.Parent == ParentId
                        from t in new List<SelectCategory>()
                        {
                            new SelectCategory()
                            {
                                ID = c.ID,
                                Name = new String('-', Level).Replace("-", "&mdash;") + c.Name,
                                Parent = c.Parent
                            }
                        }.Union(BuildSelectCategory(c.ID, Level + 1))
                        select t).ToList();
            };

            _selectCategory = BuildSelectCategory(0, 0);

            foreach (SelectCategory s in _selectCategory)
            {
                _parser.Assign("parentCategoryID", s.ID.ToString());
                _parser.Assign("parentCategoryName", s.Name.ToString());
                _parser.Parse("Main.Content.EditForm.ParentCategoryItem");
            }

            if (ID == null) //AddNew
            {
                _parser.Assign("categoryName", string.Empty);
                _parser.Assign("categoryURL", string.Empty);
                _parser.Assign("currentParentCategoryID", string.Empty);
                _parser.Assign("categoryExcerpt", string.Empty);
                _parser.Parse("Main.Content.EditForm.AddNew");
                _parser.Parse("Main.Content.EditForm");
                _parser.Parse("Main.AddNewcategories");
            }
            else //Edit
            {
                var category = (from term in _DR.Terms
                                         join taxonomy in _DR.Taxonomy on term.ID equals taxonomy.Term
                                         where taxonomy.Name.Equals(_categoryType) && term.ID.Equals(ID.Value)
                                         select new
                                         {
                                             ID = term.ID,
                                             Name = term.Name,
                                             Parent = taxonomy.Parent,
                                             Description = taxonomy.Description
                                         }).FirstOrDefault();

                if (category == null)
                {
                    _parser.Parse("Main.Content.Error");
                }
                else
                {
                    string categoryURL = _DR.Meta.Where(m => m.Object.Equals(category.ID) && m.Type.Equals("category") && m.Key.Equals("CategoryURL")).Select(m => m.Value).FirstOrDefault() ?? string.Empty;
                    string categoryImage = _DR.Meta.Where(m => m.Object.Equals(category.ID) && m.Type.Equals("category") && m.Key.Equals("CategoryImage")).Select(m => m.Value).FirstOrDefault() ?? string.Empty;

                    _parser.Assign("categoryID", category.ID.ToString());
                    _parser.Assign("categoryURL", categoryURL);
                    _parser.Assign("categoryImage", categoryImage);
                    _parser.Assign("categoryName", category.Name);
                    _parser.Assign("categoryExcerpt", category.Description);
                    _parser.Assign("currentParentCategoryID", category.Parent.ToString());

                    _parser.Parse("Main.Content.EditForm.Edit");
                    _parser.Parse("Main.Content.EditForm");
                    _parser.Parse("Main.Editcategories");
                }
            }

            _parser.Parse("Main.Content");
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }

    private void DeleteCategoriesByID(long ID)
    {
        try
        {
            Terms term = _DR.Terms.Where(t => t.ID.Equals(ID)).FirstOrDefault();

            if (term != null) _DR.DeleteObject(term);

            Taxonomy taxonomy = _DR.Taxonomy.Where(t => t.Term.Equals(ID)).FirstOrDefault();

            if (taxonomy != null) _DR.DeleteObject(taxonomy);

            List<Taxonomy> taxonomies = _DR.Taxonomy.Where(t => t.Parent.Equals(term.ID)).ToList();

            foreach (Taxonomy t in taxonomies)
            {
                t.Parent = 0;
            }

            List<Meta> metas = _DR.Meta.Where(m => m.Type.Equals("category") && m.Object.Equals(ID)).ToList();

            foreach (Meta m in metas)
            {
                _DR.DeleteObject(m);
            }

            term = null;
            taxonomy = null;
            metas = null;
            taxonomies = null;

            _DR.SaveChanges();
        }
        catch (Exception ex)
        {
            WriteError(ex);
        }
    }
}